package amalgame.ventas;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import amalgame.data.DatabaseManager;
import amalgame.entity.CustomAdapter;
import amalgame.entity.ListaActividad;
import amalgame.entity.db.OrderProduct;
import amalgame.entity.db.Product;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class OrderProductActivity extends ListaActividad {
	ListView listView;
	List<OrderProduct> orderProductList;
	List<String> productOrderListStr;
	private DatabaseManager manager;
	private Context mContext;
	private OrderProduct orderProductEdit;

	private int orderProduct_selection = 0;
	private TextView tv_title;
	
	private ImageButton btn_add;
	private Dialog customDialog;
	private OrderProduct orderProduct_edit;

	static int idOrderProduct;
	static int idProduct;

	static Product product;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.abm_product_orders);

		mContext = getApplicationContext();
		manager = DatabaseManager.getInstance();
		tv_title = (TextView) findViewById(R.id.abm_product_orders_title);
		

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			orderProduct_selection = bundle.getInt("ORDER-ID");
			tv_title.setText(getString(R.string.order_n_) + " "
					+ orderProduct_selection);
		}

		btn_add = (ImageButton) findViewById(R.id.abm_product_orders_addproduct);
		btn_add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.putExtra("ORDER-ID", orderProduct_selection);
				intent.setClass(getApplicationContext(),
						AddOrderProductActivity.class);
				startActivity(intent);

			}
		});

		listView = (ListView) getListView();
		updateList_customAdapter();
	}

	private void updateList_customAdapter() {
		orderProductList = manager.getAllOrderProductByOrderID(orderProduct_selection);
		// orderProductList = manager.getAllOrderProduct();
		productOrderListStr = new ArrayList<String>();

		if (orderProductList != null && orderProductList.size() > 0) {
			CustomAdapter_product_iconrow_custom customAdapter = new CustomAdapter_product_iconrow_custom(
					mContext, orderProductList);
			listView.setAdapter(customAdapter);
			registerForContextMenu(listView);
		} else {
			productOrderListStr.add(getResources().getString(
					R.string.no_item_added));
			CustomAdapter customAdapter = new CustomAdapter(mContext,
					productOrderListStr);
			listView.setAdapter(customAdapter);
			unregisterForContextMenu(listView);
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		updateList_customAdapter();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		// return super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.add_product_order, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem menu) {
		// TODO Auto-generated method stub
		// return super.onOptionsItemSelected(menu);

		if (menu.getItemId() == R.id.menu_addproduct_categorie) {
			Intent intent = new Intent();
			intent.setClass(mContext, CategoriesActivity.class);
			startActivity(intent);

			return true;
		}

		return false;
	}

	// ##################################################################################################################################
	// ADAPTER
	// ##################################################################################################################################
	public class CustomAdapter_product_iconrow_custom extends BaseAdapter
			implements Filterable {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		private Context mContext;
		private int id;
		private List<String> items;
		private List<OrderProduct> list;

		private LayoutInflater mInflater;
		private int mViewId;

		@SuppressWarnings("unchecked")
		public CustomAdapter_product_iconrow_custom(Context context,
				List<OrderProduct> list) {
			// super(context, R.layout.simpleiconrow, list);
			// super();
			mContext = context;
			this.list = list;

		}

		public View getView(final int position, View v, ViewGroup parent) {
			View mView = v;
			if (mView == null) {
				LayoutInflater vi = (LayoutInflater) mContext
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				mView = vi.inflate(R.layout.simpledialog_modify_delete, null);
			}

			TextView tv_title = (TextView) mView
					.findViewById(R.id.simpledialog_modify_delete_title);
			TextView tv_stock = (TextView) mView
					.findViewById(R.id.simpledialog_modify_delete_text);
			Button imb_delete = (Button) mView
					.findViewById(R.id.simpledialog_modify_delete_Delete);
			Button imb_edit = (Button) mView
					.findViewById(R.id.simpledialog_modify_delete_EDIT);

			if (list.get(position) != null) {
				tv_title.setTextColor(Color.BLACK);
				idOrderProduct = list.get(position).getOrderProductID();
				idProduct = list.get(position).getProduct_id();
				product = manager.getProductByID(idProduct);
				String nameProduct = product.getName();
				tv_title.setText(nameProduct + " codigo:" + idProduct);

				tv_stock.setTextColor(Color.BLACK);

				String desc = "Stock:" + list.get(position).getQuantity();
				tv_stock.setText(desc);

			}

			imb_delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					int id = list.get(position).getOrderProductID();
					int retDelete = manager.deleteOrderProduct(id);
					if (retDelete > 0) {
						System.out.println(" eliminacion  correcta "
								+ retDelete);
					} else {
						System.out.println(" eliminacion  iconrrecta "
								+ retDelete);
					}
					updateList_customAdapter();
				}
			});

			imb_edit.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					orderProduct_edit = list.get(position);

					// TITTLE & TEXT
					String title = getResources().getString(R.string.app_name);
					String text = getResources().getString(
							R.string.Add);

					Dialog dialog = new Dialog(OrderProductActivity.this);
					dialog = showDialogChooseNumber(text, title, id);
					dialog.show();

				}
			});

			// v.setBackground(mContext.getResources().getDrawable(
			// R.drawable.fondolist));

			return mView;
		}

		public int getCount() {
			return list.size();
		}

		public Object getItem(int position) {
			return list.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		protected List<OrderProduct> getFilteredResults(CharSequence constraint) {
			ArrayList<OrderProduct> filteredList = new ArrayList<OrderProduct>();
			for (OrderProduct c : list) {
				// //if
				// (c.getName().trim().toLowerCase().startsWith(constraint.toString().trim().toLowerCase()))
				// { // you can also use contains instead of
				// startsWith...whatever you need
				// filteredList.add(c);
				// }
			}
			return filteredList;
		}

		@Override
		public android.widget.Filter getFilter() {
			return null;
			// return new Filter() {
			//
			// @SuppressWarnings("unchecked")
			// @Override
			// protected void publishResults(CharSequence constraint,
			// FilterResults results) {
			// list_product = (List<Product>) results.values;
			// CustomAdapter_product_iconrow_custom.this.notifyDataSetChanged();
			// }
			//
			// @Override
			// protected FilterResults performFiltering(CharSequence constraint)
			// {
			//
			// List<Product> filteredResults = getFilteredResults(constraint);
			//
			// FilterResults results = new FilterResults();
			//
			// results.values = filteredResults;
			//
			// return results;
			// }
			// };
		}

	}

	// ##################################################################################################################################

	public Dialog showDialogChooseNumber(String message, String title,final int ID) {
		customDialog = new Dialog(OrderProductActivity.this);
		customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		customDialog.setContentView(R.layout.choosenumberdialog);
		customDialog.setCancelable(false);

		final TextView tv_cantity = (TextView) customDialog
				.findViewById(R.id.choosenumberdialog_textView);
		Button btn_ok = (Button) customDialog
				.findViewById(R.id.choosenumberdialog_OK);
		Button btn_cancel = (Button) customDialog
				.findViewById(R.id.choosenumberdialog_CANCEL);

		TextView tv_stock = (TextView) findViewById(R.id.iconrow_custom_tv_desc);

		final SeekBar seekBarValue10 = (SeekBar) customDialog
				.findViewById(R.id.choosenumberdialog_seekBar10);

		// tv_cantity.setText(seekBarValue100.getText().toString().trim());

		seekBarValue10
				.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

					@Override
					public void onProgressChanged(SeekBar seekBar,
							int progress, boolean fromUser) {

						// tv_cantity.setText(String.valueOf(seekBarValue10.getProgress()
						// + seekBarValue100.getProgress()*10 ));
						tv_cantity.setText(String.valueOf(seekBarValue10
								.getProgress()));
					}

					@Override
					public void onStartTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub
					}

					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub
					}
				});

		// tv_stock.setText(message);

		btn_ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				String str_quantity = tv_cantity.getText().toString();

				if (manager.getProductByID(orderProduct_selection).getQuantity() > Integer.valueOf(str_quantity)) {
					orderProduct_edit.setQuantity(Integer.valueOf(str_quantity));

					boolean ret = manager
							.updateOrderProductQuantityByyOrderId(orderProduct_edit);
					if (ret) {
						Toast.makeText(mContext,
								getString(R.string.the_item_is_updated),
								Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(mContext,
								getString(R.string.failed_to_update_the_item),
								Toast.LENGTH_LONG).show();

					}
				} else {
					Toast.makeText(mContext,
							getString(R.string.no_stock_sufficient),
							Toast.LENGTH_LONG).show();

				}

				updateList_customAdapter();
				customDialog.cancel();
				// finish();
			}
		});

		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				customDialog.cancel();
				// finish();
			}
		});
		return customDialog;
	}
}
